/**   
* @Title: UserController.java 
* @Package com.csis.system.controller 
* @Description: TODO
* @author dailey  
* @date 2012-9-27
* @version V1.0   
*/
package com.csis.system.controller;

import static com.csis.system.common.WebUtil.getSessionUser;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.csis.framework.util.jqgrid.JqGridModel;
import com.csis.framework.util.jqgrid.JqGridUtils;
import com.csis.system.common.IStaticData;
import com.csis.system.common.MD5;
import com.csis.system.common.WebUtil;
import com.csis.system.common.convert.Converter.ConvertArray;
import com.csis.system.domain.User;
import com.csis.system.domain.UserFormBean;
import com.csis.system.service.UserService;

/**
 * @author dailey
 *
 */
@Controller
@RequestMapping("/system/user")
public class UserController {
	private static final String BASE_URL = "/system/manager/admin/user/";

	protected Log log = LogFactory.getLog(UserController.class);

	@Resource
	protected UserService userService;

	@RequestMapping("/loginout")
	public ModelAndView loginout(HttpSession session) {
		session.setAttribute(IStaticData.SESSION_USER, null);
		session.invalidate();
		return new ModelAndView("redirect:toIndex.htm");
	}

	@RequestMapping("/login")
	public @ResponseBody
	String login(UserFormBean userFormBean, HttpSession httpSession) {
		int rst = 0;
		String valCode = userFormBean.getCode();
		String correctValCode = (String) httpSession.getAttribute(IStaticData.SESSION_VALDATION);
		if (StringUtils.isBlank(userFormBean.getUserName()) || StringUtils.isBlank(userFormBean.getPassWord())
				|| StringUtils.isBlank(userFormBean.getCode()))
			rst = 0;
		else if (!valCode.equalsIgnoreCase(correctValCode)) {
			rst = -2;
		} else {
			// load user info to session
			MD5 md5 = new MD5();
			User user = userService.loadUser(userFormBean.getUserName());
			if (user != null && user.getUserPassword().equals(md5.getMD5ofStr(userFormBean.getPassWord()))) {
				httpSession.setAttribute(IStaticData.SESSION_USER, user);
				rst = 1;
				if (log.isDebugEnabled())
					log.debug("UserControl>>login>>User>>" + user);
			} else {
				rst = -1;
			}
		}
		if (log.isDebugEnabled())
			log.debug("UserControl>>login>>rst>>" + rst);
		return "" + rst;
	}

	private final String URL_BASE = "/system/manager/base/personal/";

	@RequestMapping("/toIndex")
	String index() {

		return URL_BASE + "index";
	}

	@RequestMapping("/toEdit")
	String detail(Model model, HttpSession session) {
		User currentUser = getSessionUser(session);
		if (currentUser == null) {
			throw new IllegalArgumentException("Session Invalid.");
		}
		UserFormBean formBean = new UserFormBean(currentUser);
		model.addAttribute("userFormBean", formBean);

		return URL_BASE + "edit";
	}

	@RequestMapping("/edit")
	public @ResponseBody
	String edit(UserFormBean userFormBean, HttpSession session) {
		String result = "0";
		User currentUser = getSessionUser(session);
		User editUser = userFormBean.getUser();
		try {
			currentUser.setUserAddress(editUser.getUserAddress());
			currentUser.setUserPhone(editUser.getUserPhone());
			currentUser.setUserNote(editUser.getUserNote());
			userService.saveUser(currentUser);
			WebUtil.saveSessionUser(session, currentUser);
			result = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	@RequestMapping("/toPassWord")
	String passWord() {
		return URL_BASE + "password";
	}

	@RequestMapping("/resetPassword")
	@ResponseBody
	String resetPassWord(UserFormBean formBean, HttpSession session) {
		String oldPass = formBean.getPassWord();
		MD5 md5 = new MD5();
		String md5OldPass = md5.getMD5ofStr(oldPass);
		String md5NewPass = md5.getMD5ofStr(formBean.getNewPassWord());
		User currentUser = getSessionUser(session);
		if (!currentUser.getUserPassword().equals(md5OldPass)) {
			return IStaticData.ORIGINAL_PASSWORD_MISMATCH;
		} else if (currentUser.getUserPassword().equals(md5NewPass)) {
			return IStaticData.NEW_ORIGINAL_PASSWORD_SAME;
		} else if (!formBean.validataNewPass()) {
			return IStaticData.NEW_REPEAT_PASSWORD_MISMATCH;
		}

		currentUser.setUserPassword(md5NewPass);
		userService.saveUser(currentUser);
		WebUtil.saveSessionUser(session, currentUser);

		return IStaticData.NEW_ORIGINAL_REPEAT_PASSWORD_OK;
	}

	@RequestMapping("/toView")
	public String view(Model model, UserFormBean formBean) {
		Integer id = formBean.getBean().getId();
		User bean = userService.load(id);
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL + "detailuser";
	}

	@RequestMapping("/toAdd")
	public String add(Model model, HttpSession session) {
		UserFormBean formBean = new UserFormBean();
		User bean = new User();
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL + "add";
	}

	@RequestMapping("/add")
	public @ResponseBody
	String add(UserFormBean formBean) {
		String result = "0";
		User bean = formBean.getBean();
		if (bean.getUserName() == null || "".equals(bean.getUserName().trim())) {
			return result;
		}
		try {
			if (bean.getUserPassword() == null || "".equals(bean.getUserPassword())) {
				bean.setUserPassword(IStaticData.DEFALUT_USER_PASS);
			}
			String md5Pass = new MD5().getMD5ofStr(bean.getUserPassword());
			bean.setUserPassword(md5Pass);
			userService.saveUser(bean);
			result = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/_toEdit")
	public String edit(Model model, UserFormBean formBean) {
		Integer id = formBean.getBean().getId();
		User bean = userService.load(id);
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL + "modify";
	}

	@RequestMapping("/_edit")
	public @ResponseBody
	String edit(UserFormBean formBean) {
		String result = "0";
		User bean = formBean.getBean();
		if (bean.getId() == null || bean.getUserName() == null || "".equals(bean.getUserName().trim())) {
			return result;
		}
		try {
			User _temp = userService.load(bean.getId());
			bean.setUserPassword(_temp.getUserPassword());
			userService.saveUser(bean);
			result = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/list")
	public String list() {
		return BASE_URL + "listuser";
	}

	@RequestMapping("/listBy")
	public void listBy(JqGridModel model, HttpServletResponse response) {
		UserFormBean formBean = WebUtil.buildConvert(model).convertToSingle(UserFormBean.class);
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter os = null;
		try {
			userService.list(formBean);
			os = response.getWriter();
			os.write(JqGridUtils.getJSONParser(UserFormBean.class).parse(formBean).getContent());
			os.flush();
		} catch (IOException e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} catch (Exception e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
		}
	}

	@RequestMapping("/toDel")
	public @ResponseBody
	String remove(UserFormBean formBean, HttpSession session) {
		String beanIds = formBean.getBeanIds();
		ConvertArray<Integer> ids = WebUtil.buildConvert(beanIds.split(",")).convertToArray(int.class);
		User currentUser = WebUtil.getSessionUser(session);
		for (Integer id : ids) {
			if (id.equals(currentUser.getId()) || id == currentUser.getId()) {
				return "0";
			}
		}
		try {
			userService.remove(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}

	@RequestMapping("/toAssign")
	public String assign(UserFormBean formBean, Model model) {
		User bean = formBean.getBean();
		if (bean != null && bean.getId() != null) {
			bean = userService.load(bean.getId());
			formBean.setBean(bean);
		}
		model.addAttribute("formBean", formBean);
		return BASE_URL + "assign";
	}

	@RequestMapping("/assign")
	public @ResponseBody
	String assisgn(UserFormBean formBean) {
		String result = "0";
		User bean = formBean.getBean();
		String beanIds = formBean.getBeanIds();
		if (bean != null && bean.getId() != null && !StringUtils.isBlank(beanIds)) {
			ConvertArray<Integer> ids = WebUtil.buildConvert(beanIds.split(",")).convertToArray(int.class);
			try {
				userService.assignRole(bean, ids);
				result = "1";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@RequestMapping("/check")
	public @ResponseBody
	String checkExist(@RequestParam String exist) throws UnsupportedEncodingException {
		String name = "";
		if (exist != null) {
			name = URLDecoder.decode(exist, "UTF-8");
		}
		int size = userService.getUsersByName(name).size();
		return size > 0 ? "1" : "0";
	}
}
